package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    //定义一个常量
    public final static String URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 登录接口
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result login(UserLoginDTO dto) {
        if (dto.getCode() == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", dto.getCode());
        map.put("grant_type", "authorization_code");
        String body = HttpClientUtil.doGet(URL, map);
        Map parse = JSON.parseObject(body, Map.class);
        String openid = (String) parse.get("openid");
        if (openid == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        /*根据appid查询判断是否已经注册*/
        User user = userMapper.getByAppid(openid);
        //查询不到就进行注册

        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.add(user);
        }
        String token = JwtUtil.getToken(user.getId());
        UserLoginVO userLoginVO = new UserLoginVO().builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }
}
